package transfers

import (
	"net/http"
	"net/url"
	"strconv"
	"io/ioutil"
)

type HttpTransfer struct {
	Resource
}

const (
	UA = "Golang FileTransfer from Kejibo.com"
)

func (p *HttpTransfer) TotalSize() (size int, err error) {
	var req http.Request
	req.Method = "HEAD"
	req.Header = http.Header{}
	req.Header.Add("User-Agent", UA)
	req.Close = true
	//req.RequestURI = url
	req.URL, err = url.Parse(p.Url)
	if err != nil { panic(err) }

	if err != nil { panic(err) }
	header := http.Header{}
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err != nil { panic(err) }
	size, err = strconv.Atoi(resp.Header.Get("Content-Length"))
	if err != nil { panic(err) }

	return
}

func (p *HttpTransfer) PartDownload(startPos int, size int, c chan []byte) {
	var err error

	var req *http.Request
	var resp *http.Response
	req = &http.Request{}
	req.Method = "GET"
	req.Header = http.Header{}
	req.Header.Add("User-Agent", UA)
	req.Close = true
	//req.RequestURI = url
	req.URL, err = url.Parse(p.Url)
	if err != nil { panic(err) }

	if err != nil { panic(err) }
	header := http.Header{}
	header.Set("Range", "bytes=" + strconv.Itoa(int(startPos)) + "-" + strconv.Itoa(startPos + size - 1))
	req.Header = header
	resp, err = http.DefaultClient.Do(req)
	if err != nil { panic(err) }

	buf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	c <- buf
}

func NewHttpTransfer(resource Resource) *HttpTransfer {
	return &HttpTransfer{resource}
}